package test01.demo06;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.util.Arrays;

/**
 * 给定实体类Person p=new Person(“张飞”，18)，使用反射给name属性、age属性赋值赋值为 “刘备”，34
 */
public class ClassMethod {

    public static void attributeAssignment(Class clazz) throws Exception {
        //当前类中所有的构造方法按照参数进行查找
        Constructor currentClassConstructor = clazz.getDeclaredConstructor(String.class,int.class);
        //System.out.println(currentClassConstructor);

        //创建Person类的实例
        Object person = currentClassConstructor.newInstance("张飞",18);

        //获取name属性并设置可访问
        Field nameField = clazz.getDeclaredField("name");
        nameField.setAccessible(true);
        nameField.set(person,"刘备");

        //获取age属性并设置可访问
        Field ageField = clazz.getDeclaredField("age");
        ageField.setAccessible(true);
        ageField.set(person,34);

        System.out.println(person);
    }

    public static void main(String[] args) throws Exception {
        Person p = new Person("张飞",18);
        Class clazz = p.getClass();
        attributeAssignment(clazz);
    }
}
